package org.duiduo.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.duiduo.util.ThreadMDCUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.ValidatorException;

/**
 * 全局过滤器
 *
 * @author liangze
 * @date 2025/9/28 9:44
 */
@Slf4j
@Component
public class GlobalFilter implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        ThreadMDCUtil.setTraceIdIfAbsent();
        try {
            chain.doFilter(ctx);
        } catch (ValidatorException e) {
            log.warn("异常:", e);
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (StatusException e) {
            log.warn("异常:", e);
            // 自带状态码的异常，包含鉴权异常、数据校验异常、自定义业务异常
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (IllegalArgumentException e) {
            log.warn("异常:", e);
            ctx.render(Result.failure(500, e.getMessage()));
        } catch (Throwable e) {
            log.error("异常:", e);
            ctx.render(Result.failure(500, "服务端运行出错"));
        }
    }

}
